package com.example.studyPlatform.service;

import com.example.studyPlatform.bean.User;
import com.example.studyPlatform.exception.InvalidValidationException;
import com.example.studyPlatform.kit.EmailUtils;
import com.example.studyPlatform.mapper.UserMapper;
import com.example.studyPlatform.service.protocol.RegisterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class RegisterServiceImpl implements RegisterService {

    UserMapper userMapper;
    EmailUtils emailUtils;

    public RegisterServiceImpl(UserMapper userMapper, EmailUtils emailUtils) {
        this.userMapper = userMapper;
        this.emailUtils = emailUtils;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Optional<User> register(User user, String verCode) {
        if(emailUtils.verification(user.getEmail(),verCode)){
            userMapper.register(user);
            return Optional.of(user);
        }else {
            throw new InvalidValidationException(user);
        }
    }

    @Override
    public boolean checkUserName(String username) {
        return !userMapper.hasUserName(username);
    }
}
